<template>
    <el-row>
        <!-- 头部 -->
        <el-col :span="24">
            <el-card shadow="hover">
                <el-breadcrumb :separator-icon="ArrowRightBold">
                    <el-breadcrumb-item :to="{ path: '/admin_index' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
                    <el-breadcrumb-item>用户数据总览</el-breadcrumb-item>
                </el-breadcrumb>
            </el-card>
        </el-col>
        <div style="padding: 5px;"></div>
        <!-- 内容区域 -->
        <el-col :span="24">
            <el-card shadow="hover" >
                <template #header>
                  <div style="display: flex; justify-content: space-between;">
                    <div style="display: flex; align-items: center;">
                        <el-input style="width: 260px;" v-model="inputval" placeholder="请输入UID、手机、昵称、备注" />
                        <div style="padding: 5px;"></div>
                        <el-select   style="width: 150px;" v-model="group_id" placeholder="请选择用户分组">
                          <el-option label="全部" value="">全部</el-option>
                          <el-option label="未分组" value="0">未分组</el-option>
                          <el-option :label="item.name" :value="item.id" v-for="item in group.list">{{item.name}}</el-option>
                        </el-select>
                        <div style="padding: 5px;"></div>
                        <el-date-picker v-model="page.time_date[0]" :default-value="page.time_date[0]" type="datetime" placeholder="开始日期" style="width: 180px;" />
                        <div style="width: 15px"></div>
                        <el-date-picker v-model="page.time_date[1]" :default-value="page.time_date[1]" default-time="12:00:00" type="datetime" placeholder="结束日期" style="width: 180px;" />
                        <div style="padding: 5px;"></div>

                        <el-button type="primary" :icon="Search" @click="inputSearch()">搜索</el-button>
                    </div>

<!--                    <div style="display: flex; align-items: center;">-->
<!--                      <el-radio-group v-model="page.pagesize" @change="pageSelect">-->
<!--                     -->
<!--                        <el-radio-button label="50">50</el-radio-button>-->
<!--                        <el-radio-button label="100">100</el-radio-button>-->
<!--                        <el-radio-button label="500">500</el-radio-button>-->
<!--                        <el-radio-button label="1000">1000</el-radio-button>-->
<!--                      </el-radio-group>-->
<!--                    </div>-->
                  </div>
                  <div style="overflow: hidden;width: 100%;margin-top: 10px;">
                    <div
                        style="font-size: 15px; color: #666666; font-weight: 600; background-color: #efefef; padding:6px 10px; border-radius: 5px;float:left;margin-right:20px;">
                      <span style="color: red;">总剩余分：<span style="color: green;">{{ count.zsyfs }}</span></span>
                      <span style="color: red;margin-left: 20px;">总下注人数：<span style="color: green;">{{
                          count.zdzrs
                        }}</span></span>
                      <span style="color: red;margin-left: 20px;">总输赢：<span style="color: green;">{{
                          count.zsy.toFixed(2)
                        }}</span></span>
                      <span style="color: red;margin-left: 20px;">总流水：<span style="color: green;">{{ count.zls }}</span></span>
                      <span style="color: red;margin-left: 20px;">总上分：<span style="color: green;">{{ count.zsf }}</span></span>
                      <span style="color: red;margin-left: 20px;">总下分：<span style="color: green;">{{ count.zxf }}</span></span>
                      <span style="color: red;margin-left: 20px;">总彩金：<span style="color: green;">{{ count.zcj }}</span></span>
                      <span style="color: red;margin-left: 20px;">总佣金：<span style="color: green;">{{ count.zyj }}</span></span>
                    </div>

                  </div>
                  <div style="overflow: hidden;margin-top: 10px;">
                    <div style="float:left">
                      <el-radio-group v-model="showIndex" @change="changeShowIndex">
                        <el-radio-button label="1">A版</el-radio-button>
                        <el-radio-button label="2">B版</el-radio-button>
                        <el-radio-button label="3">C版</el-radio-button>
                        <el-radio-button label="4">D版</el-radio-button>
                      </el-radio-group>
                    </div>
                    <div style="float:left;margin-left:10px;">
                      显示更多数据
                      <el-tooltip :content="lookOpen == 1 ? '显示开启' : '显示关闭'" placement="top">
                        <el-switch v-model="lookOpen" :active-value="1" :inactive-value="0"  @change="openLook"></el-switch>
                      </el-tooltip>
                    </div>
                  </div>
                </template>

                <!-- 表格 -->
                <el-table :data="tableData.list" :border="true" style="width: 100%" v-if="showIndex==1 || showIndex==3">

                    <el-table-column label="用户详情"  class-name="success">
                      <template #default="scope">
                        <div>{{ scope.row.nickname }} </div>
                        <div>{{ thPhone(scope.row.phone) }} </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="账单名"  class-name="success">
                      <template #default="scope">
                        <div>{{ scope.row.remark }}  </div>
                        <div>{{ groupArr.get(scope.row.group_id) }} </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="总局数" class-name="success">
                        <template #default="scope">
                            {{ scope.row.tz_zhun_shu }} (单)
                        </template>
                    </el-table-column>

                    <el-table-column label="用户流水" prop="tz_zhun_money" class-name="qing">
                      <template #default="scope">
                        <div>{{ scope.row.tz_zhun_money }}</div>
                        <div v-if="scope.row.tz_zhun_money>0 && role.includes('rest') && showResetButton">
                          <el-popconfirm  title="确定重置吗？" @confirm="restLs(scope.row.uid)" >
                            <template #reference>
                              <el-button  type="success" >重置</el-button>
                            </template>
                          </el-popconfirm >

                        </div>

                      </template>
                    </el-table-column>
<!--                    <el-table-column label="总中奖金额" prop="tz_zhun_amoney" class-name="qing"></el-table-column>-->
                  <el-table-column label="非中奖投注额" prop="fls_money" class-name="qing" v-if="showIndex==3"></el-table-column>
                    <el-table-column label="用户输赢" class-name="danger">
                        <template #default="scope">
                            <div v-if="(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney) > 0">+{{ truncateDecimal(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney, 2) }}</div>
            <div v-else>{{ truncateDecimal(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney, 2) }}</div>
                        </template>
                    </el-table-column>

                    <el-table-column label="总上分" class-name="success">
                        <template #default="scope">
                            {{ scope.row.zcz_money }}
                          <div>(充值{{ scope.row.cz_money }})</div>
                          <div><sapn style="color:red">(彩金{{ scope.row.ht_voucher }})</sapn></div>
                          <div><sapn style="color:red">(佣金{{ scope.row.yj_money }})</sapn></div>
                        </template>
                    </el-table-column>

                    <el-table-column label="总下分" class-name="success">
                        <template #default="scope">
                            {{scope.row.tx_money }}
                        </template>
                    </el-table-column>

                    <el-table-column label="用户余额" class-name="qing">
                      <template #default="scope">
                        <div>{{Number(scope.row.money) + Number(scope.row.voucher)}}</div>
                        <div>(余额：{{scope.row.money}})</div>
                        <div>(彩金：{{scope.row.voucher}})</div>
                      </template>
                    </el-table-column>
<!--                    <el-table-column label="当前代理余额" prop="agent_money" class-name="qing"></el-table-column>-->

                </el-table>
              <!-- 表格 -->
              <el-table :data="tableData.list" :border="true" style="width: 100%" v-else>

                <el-table-column label="UID" prop="uid" class-name="success"></el-table-column>
                <el-table-column label="用户名" prop="nickname" class-name="success"></el-table-column>
                <el-table-column label="备注" prop="remark" class-name="success"></el-table-column>
                <el-table-column label="总投注单数" class-name="success">
                  <template #default="scope">
                    {{ scope.row.tz_zhun_shu }} (单)
                  </template>
                </el-table-column>
                <el-table-column label="非六合投注额" prop="flh_money" class-name="qing" v-if="showIndex==4"></el-table-column>
                <el-table-column label="总投注金额" prop="tz_zhun_money" class-name="qing"></el-table-column>
                <el-table-column label="总中奖金额" prop="tz_zhun_amoney" class-name="qing"></el-table-column>

                <el-table-column label="总输赢" class-name="danger">
                  <template #default="scope">
                    <div v-if="(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney) > 0">+{{ truncateDecimal(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney, 2) }}</div>
            <div v-else>{{ truncateDecimal(scope.row.tz_zhun_amoney+ scope.row.hb_ymoney - scope.row.tz_zhun_money_no_rest- scope.row.hb_smoney, 2) }}</div>
                  </template>
                </el-table-column>

                <el-table-column label="总充值金额" class-name="success">
                  <template #default="scope">
                    {{ Math.round(scope.row.cz_money) }}
                  </template>
                </el-table-column>

                <el-table-column label="总提现金额" class-name="success">
                  <template #default="scope">
                    {{ Math.round(scope.row.tx_money) }}
                  </template>
                </el-table-column>

                <el-table-column label="当前余额" class-name="qing">
                    <template #default="scope">
                        {{Number(scope.row.money)}}
                    </template>
                </el-table-column>
                <el-table-column label="当前彩金" prop="voucher" class-name="qing"></el-table-column>
                <el-table-column label="当前代理余额" prop="agent_money" class-name="qing"></el-table-column>

              </el-table>
                <!-- 分页 -->
                <div style="padding: 10px;"></div>
                <el-pagination small background v-model:currentPage="page.pagenum" :page-size="page.pagesize"
                    :page-sizes="[50,100,200,300,500]" :small="small" layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total" @size-change="pageSelect" @current-change="handleCurrentChange" />

            </el-card>
        </el-col>
    </el-row>
</template>

<script setup>

import { ref, reactive, onMounted, computed } from 'vue'
import { request_post } from '@/common/axios/request.js'
import { success, error } from '@/common/tool/message.js'
import { ArrowRightBold, UserFilled, Search } from '@element-plus/icons-vue'


const tableData = reactive({ list: [] })
const group = reactive({ list: [] })
const groupArr = ref(null)
const showIndex = ref(1)
const count = reactive({
  zsyfs:0,
  zdzrs:0,
  zsy:0,
  zls:0,
  zsf:0,
  zxf:0,
  zcj:0,
  zyj:0,
})

function thPhone(phone){
  if(!phone){
    return ''
  }
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

function changeShowIndex(){
  localStorage.setItem('showIndex',showIndex.value)
  console.log(showIndex.value,'changeShowIndex');
}

const role = ref([]);
const showResetButton = ref(false);

// 判断是否为当天数据（开始时间和结束时间都必须精确是今天）
function checkIsTodayData() {
  if (!page.time_date || page.time_date.length !== 2) {
    showResetButton.value = false;
    return;
  }
  
  try {
    const today = new Date();
    const startDate = new Date(page.time_date[0]);
    const endDate = new Date(page.time_date[1]);
    
    // 获取日期字符串（只比较日期部分，格式：YYYY/MM/DD）
    const startDay = startDate.toLocaleDateString();
    const endDay = endDate.toLocaleDateString();
    const todayDay = today.toLocaleDateString();
    
    // 开始时间和结束时间都必须精确是今天
    const isToday = startDay === todayDay && endDay === todayDay;
    
    showResetButton.value = isToday;
    
    
    return isToday;
  } catch (e) {
    
    showResetButton.value = false;
    return false;
  }
}

onMounted(() => {
  showIndex.value = localStorage.getItem('showIndex')?localStorage.getItem('showIndex'):1

  admin_users_index()

  const list = JSON.parse(window.localStorage.getItem('menus_data'))
  let menu = [];
  for(let key in list){
    if(list[key].name=='用户管理'){
      menu = list[key]
    }
  }
  console.log(menu,'menu');
  let child = [];
  for(let i in menu.children){
    if(menu.children[i].name=='用户数据总览'){
      child = menu.children[i]
    }
  }
  let roleArr =[];

  for(let i in child.children){
    roleArr.push(child.children[i].role)
  }
  role.value = roleArr

})

const group_id = ref('')

// 搜索
const inputval = ref('')
function inputSearch() {
    page.uid = inputval.value
    page.group_id = group_id.value

    admin_users_index()
}

const lookOpen = ref(0);
// 获取用户列表
function admin_users_index() {
    request_post('/admin_users_count', page).then((res) => {

        if (res.data.code == 200) {
            tableData.list = res.data.data.data
            lookOpen.value = res.data.data.look_open

            page.total = res.data.data.total
			      group.list = res.data.data.group_list
            groupArr.value = new Map(group.list.map(item=>[item.id,item.name]));
            count.zsyfs = res.data.data.count.zsyfs
            count.zdzrs = res.data.data.count.zdzrs
            count.zsy = res.data.data.count.zsy
            count.zls = res.data.data.count.zls
            count.zsf = res.data.data.count.zsf
            count.zxf = res.data.data.count.zxf
            count.zcj = res.data.data.count.zcj
            count.zyj = res.data.data.count.zyj
            checkIsTodayData() // 点击搜索时判断是否为当天数据
        } else {
            return error(res.data.msg)
        }
    })

}

var now_date = new Date();
var now_date2 = new Date();

var year = now_date.getFullYear();
var month = now_date.getMonth() + 1; // 月份从0开始，所以要加1
var day = now_date.getDate();
now_date.setHours(23, 59, 59);
now_date2.setHours(0,0,0)
const page = reactive({
    uid: '',
	  group_id: group_id,
    time_date: [
      now_date2,
        now_date
	],
    pagenum: 1,
    pagesize: 50,
    total: 0
})

function openLook(e){

  request_post('/admin_config_create', {'look_open':e}).then(res => {

    if (res.data.code == 200) {
      page.pagenum = 1
      admin_users_index()
      return success(res.data.msg)

    } else {
      return error(res.data.msg)
    }
  })
}
function pageSelect(val){
  page.pagenum = 1
  page.pagesize = val
  console.log(val,'pageSelect');
  admin_users_index()
}
function handleSizeChange(val) {
    page.pagenum = val
    admin_users_index()
}
function handleCurrentChange(val) {
    page.pagenum = val
    admin_users_index()
}
let restData = reactive({})
function restLs(uid){
  restData = {...page}
  restData.uid = uid;

  request_post('/admin_users_rest_ls', restData).then((res) => {
    if (res.data.code == 200) {
      admin_users_index()
      return success('重置成功')

    } else {
      return error('重置失败')
    }
  })
}

// 截断小数，不四舍五入
function truncateDecimal(num, decimalPlaces) {
  const factor = Math.pow(10, decimalPlaces)
  return Math.floor(num * factor) / factor
}

</script>

<style>
	.success{
		background-color: #90EE90;
		font-weight: bold;
	}
	.qing{
		background-color: #CFE2FF;
		font-weight: bold;
	}
	.danger{
		background-color: #FFBCCB;
		font-weight: bold;
	}
</style>
